package org.windowkit.toolkit.widget.tree;

import java.io.File;
import java.io.FileFilter;

import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;

public class FileTreeModel extends DefaultTreeModel {




    /**
	 *
	 */
	private static final long serialVersionUID = -7196995294147558070L;
	private String rootFilePath;
    private FileFilter filter;

    @SuppressWarnings("unused")
    private final static FileFilter NO_FILTER = new FileFilter(){
        public boolean accept( final File pathname) {
            return true;
        }
    };

    public FileTreeModel(){
        this(null, null);
    }

    public FileTreeModel(final File root, final FileFilter filter){
        super(new DefaultMutableTreeNode(), true);

        if(filter != null){
            this.filter = filter;
        }else{
            this.filter = NO_FILTER;
        }

        if(root != null){
            setRootFile(root);
        }else{
            //TODO maybe have some generic path

        }




    }


    public void setRootFile(final File f){
        if(f != null && f.exists()){
            this.rootFilePath = f.getPath();
            setRoot(createFileTree(f, filter));
        }else{
            this.rootFilePath = null;
            setRoot(null);
        }
    }



    public void refresh(){
        if(this.rootFilePath != null){
            setRootFile(new File(this.rootFilePath));
        }
    }


    public void setFileFilter(final FileFilter filter){
        if(filter != null){
            this.filter = filter;
        }else{
            this.filter = NO_FILTER;
        }
    }

    private FileNode createFileTree(final File rooot, final FileFilter filt){
        FileNode node = new FileNode(rooot);

        if(rooot.isDirectory()){
            File[] files = rooot.listFiles(filt);
            if(files != null){
                for(File file : files){
                    node.add(createFileTree(file, filt));
                }
            }
        }
        return node;
    }





}
